using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Win32;
using OfficeOpenXml;
using System.IO;
using ErpManager.WPF.Models;
using ErpManager.WPF.Services;

namespace ErpManager.WPF.ViewModels
{
    public class LogViewModel : INotifyPropertyChanged
    {
        private readonly ApplicationDbContext _context;
        private DateTime _startDate = DateTime.Today.AddDays(-30);
        private DateTime _endDate = DateTime.Today;
        private string _selectedModule = string.Empty;
        private string _searchText = string.Empty;
        private string _errorMessage = string.Empty;
        private bool _isLoading;

        public ObservableCollection<OperationLog> OperationLogs { get; } = new();
        public ObservableCollection<string> Modules { get; } = new();

        public event PropertyChangedEventHandler? PropertyChanged;

        public DateTime StartDate
        {
            get => _startDate;
            set
            {
                _startDate = value;
                OnPropertyChanged(nameof(StartDate));
                _ = LoadOperationLogs();
            }
        }

        public DateTime EndDate
        {
            get => _endDate;
            set
            {
                _endDate = value;
                OnPropertyChanged(nameof(EndDate));
                _ = LoadOperationLogs();
            }
        }

        public string SelectedModule
        {
            get => _selectedModule;
            set
            {
                _selectedModule = value;
                OnPropertyChanged(nameof(SelectedModule));
                _ = LoadOperationLogs();
            }
        }

        public string SearchText
        {
            get => _searchText;
            set
            {
                _searchText = value;
                OnPropertyChanged(nameof(SearchText));
                _ = LoadOperationLogs();
            }
        }

        public string ErrorMessage
        {
            get => _errorMessage;
            set
            {
                _errorMessage = value;
                OnPropertyChanged(nameof(ErrorMessage));
            }
        }

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged(nameof(IsLoading));
            }
        }

        public ICommand ExportToExcelCommand { get; }
        public ICommand RefreshCommand { get; }

        public LogViewModel(ApplicationDbContext context)
        {
            _context = context;
            ExportToExcelCommand = new RelayCommand(async () => await ExportToExcel());
            RefreshCommand = new RelayCommand(async () => await LoadOperationLogs());

            // 初始化模块列表
            Modules.Add(string.Empty); // 添加一个空选项
            Modules.Add("用户管理");
            Modules.Add("产品管理");
            Modules.Add("经销商管理");
            Modules.Add("出库管理");

            // 初始加载日志
            _ = LoadOperationLogs();
        }

        private async Task LoadOperationLogs()
        {
            try
            {
                IsLoading = true;
                ErrorMessage = string.Empty;

                var query = _context.OperationLogs
                    .Where(l => l.OperationTime >= StartDate && l.OperationTime <= EndDate.AddDays(1));

                if (!string.IsNullOrWhiteSpace(SelectedModule))
                {
                    query = query.Where(l => l.Module == SelectedModule);
                }

                if (!string.IsNullOrWhiteSpace(SearchText))
                {
                    query = query.Where(l => l.UserName.Contains(SearchText) ||
                                           l.Operation.Contains(SearchText) ||
                                           l.Details.Contains(SearchText));
                }

                var logs = await query
                    .OrderByDescending(l => l.OperationTime)
                    .ToListAsync();

                OperationLogs.Clear();
                foreach (var log in logs)
                {
                    OperationLogs.Add(log);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"加载操作日志失败: {ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task ExportToExcel()
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel files (*.xlsx)|*.xlsx",
                Title = "选择导出位置",
                FileName = $"操作日志_{DateTime.Now:yyyyMMdd}.xlsx"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using var package = new ExcelPackage();
                    var worksheet = package.Workbook.Worksheets.Add("操作日志");

                    // 添加标题行
                    worksheet.Cells[1, 1].Value = "用户名";
                    worksheet.Cells[1, 2].Value = "模块";
                    worksheet.Cells[1, 3].Value = "操作";
                    worksheet.Cells[1, 4].Value = "详情";
                    worksheet.Cells[1, 5].Value = "IP地址";
                    worksheet.Cells[1, 6].Value = "操作时间";

                    // 添加数据
                    int row = 2;
                    foreach (var log in OperationLogs)
                    {
                        worksheet.Cells[row, 1].Value = log.UserName;
                        worksheet.Cells[row, 2].Value = log.Module;
                        worksheet.Cells[row, 3].Value = log.Operation;
                        worksheet.Cells[row, 4].Value = log.Details;
                        worksheet.Cells[row, 5].Value = log.IpAddress;
                        worksheet.Cells[row, 6].Value = log.OperationTime;
                        row++;
                    }

                    // 设置列宽
                    worksheet.Columns.AutoFit();

                    // 保存文件
                    await package.SaveAsAsync(new FileInfo(saveFileDialog.FileName));
                    ErrorMessage = "导出成功！";
                }
                catch (Exception ex)
                {
                    ErrorMessage = $"导出失败: {ex.Message}";
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
